<?php

class PartnerAPIService extends FServiceBase
{
    /**
     * Get a Partner model given its ID
     *
     * @param int id Partner ID
     * @return FServiceModel
     */
    public function get($params)
    {
        $model = Partner::model()->findByPk($this->getParam($params, 'id', 0));
        if (!$model)
            $this->result->fail(ERROR_INVALID_DATA, Yii::t('Partner.Partner', 'Invalid ID.'));
        $this->result->processed('model', $model);
        return $this->result;
    }

    public function save($params)
    {
        $model = $this->getModel($params['Partner'], 'Partner');
        $this->result->processed('model', $model);
        $model->update_time = date('Y-m-d H:i:s');

        if (!$model->validate()) {
            $this->result->fail(ERROR_INVALID_DATA, Yii::t('Partner.Partner', 'Submitted data is missing or invalid.'));
            Yii::trace($model->getErrors());
        } elseif ($this->getParam($params, 'validateOnly', 0) == TRUE) {
            return $this->result;
        } elseif (!$model->save(false)) {
            // we can save without validation as the model has been validated
            $this->result->fail(ERROR_HANDLING_DB, Yii::t('Partner.Partner', 'Error while saving submitted data into database.'));
        }
        return $this->result;
    }

    public function delete($params)
    {
        $ids = $this->getParam($params, 'ids', array());
        if ($ids == 0) {
            return $this->result->fail(ERROR_INVALID_DATA, Yii::t('Partner.Partner', 'Invalid ID.'));
        }

        if (!is_array($ids)) $ids = array($ids);
        foreach ($ids as $id)
        {
            $model = Partner::model()->findByPk($id);
            if (is_null($model))
            {
                $this->result->fail(ERROR_INVALID_DATA, Yii::t('Partner.Partner', 'Partner is not found.'));
                continue;
            }    
            LanguagePartner::model()->deleteAll('partner_id=:partnerId',array(':partnerId'=>$model->id));
            $model->delete();
        }
        return $this->result;
    }
    
    public function setStatus($params = array())
    {
        $status = $this->getParam($params, 'status', '');
        $id = $this->getParam($params, 'id', 0);

        if ($status != 'active' && $status != 'inactive')
            return $this->result->fail(0, 'Invalid status.');

        $ret = Partner::model()->updateByPk($id, array('status' => ($status == 'active' ? 0 : 1)));
        $this->result->processed('success', $ret);
    }
}